package com.project.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @Title: UserController
 * @Package: com.project.controller
 * @Description:
 * @Author: Liang-Xie
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("getLoginUser")
    public UserBean getLoginUser(HttpServletRequest req) {
        UserBean user = (UserBean) req.getSession().getAttribute("loginUser");
        return user;
    }

    @RequestMapping("login")
    public String login(String userName, String pwd, HttpServletRequest req) {
        UserBean user = userService.login(userName, pwd);
        if (user == null) {
            return "no";
        } else {
            req.getSession().setAttribute("loginUser", user);
            return "ok";
        }
    }

    @RequestMapping("findByItem")
    public IPage<UserBean> findByItem(Integer pageNO, String name) {
        return userService.findByItem(pageNO, name);
    }


    @RequestMapping("add")
    public String add(UserBean user, Integer[] roleIdArray) {
        if (userService.add(user, roleIdArray)) {
            return "ok";
        } else {
            return "no";
        }
    }

    @RequestMapping("del")
    public String del(Integer userId,HttpServletRequest req) {
        UserBean userBean = (UserBean) req.getSession().getAttribute("loginUser");
        if (userBean.getId()==userId){
            return "no";
        }else{
            userService.del(userId);
            return "ok";
        }
    }

    @RequestMapping("findById")
    public UserBean findById(Integer userId) {
        return userService.findById(userId);
    }
    @RequestMapping("updateRole")
    public String updateRole(Integer userId, Integer[] roleIdArray) {
        userService.updateRole(userId, roleIdArray);
        return "ok";
    }
    @RequestMapping("updatePwd")
    public String updateUserPwd(String newPwd,HttpServletRequest req) {
        UserBean userBean = (UserBean) req.getSession().getAttribute("loginUser");
        if (!userBean.getPassword().equals(newPwd)) {
            userService.updatePwd(userBean.getId(), newPwd);
            return "ok";
        } else {
            return "no";
        }
    }
}
